import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Button,
  Select,
  Cascader,
  Descriptions,
  Pagination,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import { PartTimeWageListData, PartTimeWageListParams } from './data';
import AddOrUpdate from './components/AddOrUpdate';

const { Option } = Select;

const colContentTitle = {
  height: '32px',
  lineHeight: '32px',
  fontSize: 12,
  paddingLeft: 16,
  backgroundColor: 'rgba(0,0,0,0.03)',
  borderBottom: '1px solid rgba(0,0,0,0.25)',
};

const { pathname } = window.location;
const { Item } = Descriptions;
interface PartTimeWageAllocationListProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: PartTimeWageListData;
  INITINFO: any;
  screen: string;
}

interface PartTimeWageAllocationListState {
  searchValues: PartTimeWageListParams,
  saveVisible: boolean;
  detail: any;
}

@connect(({
  partTimeWageAllocationList: { dataInfo },
  common: { INITINFO },
  global: { screen },
}: any) => ({
  dataInfo,
  INITINFO,
  screen,
}))

class PartTimeWageAllocationListElem extends Component<PartTimeWageAllocationListProps,
PartTimeWageAllocationListState> {
  state: PartTimeWageAllocationListState = {
    searchValues: {
      provinceCode: '',
      cityCode: '',
      countyCode: '',
      logisId: '',
      pageIndex: 1,
      pageSize: 20,
    },
    saveVisible: false,
    detail: {},
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        pageIndex: Number(pageIndex) || 1,
        pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
      },
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
    this.fetchAction('common/fetchAddressList');
    this.fetchAction('common/fetchLogisList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    if (!_.isEqual(this.state, prevState)) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const {
      searchValues: {
        pageIndex,
        pageSize,
        ...values
      },
    } = this.state;
    const params = this.turnValuesType(values);

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  }

  turnValuesType = (values: any) => ({ // 转换数据类型
    ...values,
    area: values.area ? JSON.parse(values.area) : [],
    logisId: values.logisId && Number(values.logisId),
  })

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    const { area, ...query }: any = searchValues;
    const areaCodes = area ? JSON.parse(area) : [];
    const params = {
      ...query,
      provinceCode: areaCodes[0],
      cityCode: areaCodes[1],
      countyCode: areaCodes[2],
    };
    return params;
  }

  handleChangeSaveModal = (saveVisible: boolean, values: any = {}) => {
    this.setState({ saveVisible, detail: values });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const query = {
        ...searchValues,
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { area } = values;
      if (area && area.length) query.area = JSON.stringify(area);

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '兼职工资配置',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '兼职工资配置',
      url: pathname,
      isTopMenu: true,
    });
  }

  handleSelectPage:any = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '兼职工资配置',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `partTimeWageAllocationList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      form: { getFieldDecorator },
      dataInfo: { list = [], count = 0 },
      INITINFO: { addressList, logisList },
    } = this.props;
    const {
      saveVisible,
      detail,
      searchValues,
    } = this.state;

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={6} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="　省市区" colon={false}>
                  {getFieldDecorator('area')(
                    <Cascader changeOnSelect options={addressList} placeholder="请选择" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginB12"
              onClick={() => this.handleChangeSaveModal(true)}
            >新建
            </Button>
          </div>
          <div style={{ overflowX: 'auto' }}>
            {list.map((item: any) => (
              <Row
                className="paddingB16 marginB20 partTime"
                key={item.id}
                style={{
                  minWidth: 1000,
                  border: '1px solid #eee',
                }}
              >
                <Col span={4}>
                  <div style={colContentTitle}>物流中心</div>
                  <Descriptions column={1} className="marginT10 paddingL16">
                    <Item>{item.logisName}</Item>
                  </Descriptions>
                </Col>
                <Col span={5}>
                  <div style={colContentTitle}>项目 | 单价(元/件)</div>
                  <Descriptions column={1} className="paddingT10 paddingL16">
                    <Item label="　　　　　接驳">{(item.transhipPrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　　分拣">{(item.sortingPrice / 100).toFixed(2)}</Item>
                    <Item label="接驳分拣二合一">{(item.sortingTwoInOnePrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　　投递">{(item.deliveryPrice / 100).toFixed(2)}</Item>
                    <Item label="批量投递三合一">{(item.deliveryThreeInOnePrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　　盘点">{(item.inventoryPrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　问题件">{(item.problemPrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　　揽件">{(item.sendPrice / 100).toFixed(2)}</Item>
                    <Item label="　　　　　取件">{(item.pickupPrice / 100).toFixed(2)}</Item>
                    <Item label="　　　OCR校验">{(item.ocrCheckPrice / 100).toFixed(2)}</Item>
                  </Descriptions>
                </Col>
                <Col span={6}>
                  <div style={colContentTitle}>创建人 | 创建时间</div>
                  <Descriptions column={1} className="paddingT10 paddingL16">
                    <Item>{item.createUserName} | {item.createTime}</Item>
                  </Descriptions>
                </Col>
                <Col span={6}>
                  <div style={colContentTitle}>修改人 | 修改时间</div>
                  <Descriptions column={1} className="paddingT10 paddingL16">
                    <Item>{item.updateUserName} | {item.updateTime}</Item>
                  </Descriptions>
                </Col>
                <Col span={3}>
                  <div style={colContentTitle}>操作</div>
                  <div className="paddingT10 paddingL16">
                    <span
                      className="operLink"
                      onClick={() => this.handleChangeSaveModal(true, item)}
                    >编辑
                    </span>
                  </div>
                </Col>
              </Row>
            ))}
          </div>
          <Pagination
            current={searchValues.pageIndex}
            total={count}
            showSizeChanger
            showQuickJumper
            pageSizeOptions={['10', '20', '50', '100']}
            showTotal={() => `共${count || 0}条数据`}
            onChange={this.handleSelectPage}
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              paddingBottom: 20,
              paddingRight: 24,
            }}
          />
        </Card>
        <AddOrUpdate
          saveVisible={saveVisible}
          detail={detail}
          searchValues={searchValues}
          changeSaveModal={this.handleChangeSaveModal.bind(this)}
        />
      </Fragment>
    );
  }
}

export default Form.create<PartTimeWageAllocationListProps>()(PartTimeWageAllocationListElem);
